#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> 
#include <unistd.h>

#define BUFSIZE	16	

int mycopy_reverse(int rfd, int wfd);
int reverse_string(char *p);

int main(int argc, char *argv[])
{
	int fd1, fd2;

	if (argc < 3)
		return 1;
	
	fd1 = open(argv[1], O_RDONLY);
	if (-1 == fd1) {
		perror("open()");
		return 1;
	}
	fd2 = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0666);
	if (-1 == fd2) {
		perror("open()");
		close(fd1);
		return 1;
	}

	mycopy_reverse(fd1, fd2);

	close(fd1);
	close(fd2);

	return 0;
}

int mycopy_reverse(int rfd, int wfd)
{
	char buf[BUFSIZE + 1] = {};
	int cnt;
	size_t size, len;

	size = lseek(rfd, 0, SEEK_END);

	while (size > 0) {
		memset(buf, 0, BUFSIZE + 1);
		if (size > BUFSIZE) {
			len = BUFSIZE;
		} else 
			len = size;
		size -= len;
		lseek(rfd, size, SEEK_SET);
		cnt = read(rfd, buf, len);
		if (-1 == cnt) {
			perror("read()");
			return -1;
		}
		reverse_string(buf);
		write(wfd, buf, cnt);	
	}

	return 0;
}

int reverse_string(char *p)
{
	int i, j;
	char c;

	for (i = 0, j = strlen(p) - 1; i < j; i++, j--) {
		c = p[i];
		p[i] = p[j];
		p[j] = c;	
	}

	return 0;
}




